package com.chen.springboot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.springboot.dto.UserDto;
import com.chen.springboot.entity.User;
import com.chen.springboot.exception.ServiceException;
import com.chen.springboot.mapper.UserMapper;
import com.chen.springboot.service.UserService;
import com.chen.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null)
            throw new ServiceException("-1", "用户名已经存在，请重新输入");
        userMapper.insert(user);
    }

    @Override
    public UserDto login(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res == null)
            throw new ServiceException("404", "用户名不存在");
        if (!res.getPassword().equals(user.getPassword()))
            throw new ServiceException("404", "密码错误");
        // 生成 token，用户id保存到token里面，然后密码用于加密
        String token = TokenUtils.genToken(res.getId().toString());
        return new UserDto(res, token);
    }

    @Override
    public UserDto manageLogin(User user) {
        // 因为我们用户名是唯一的，所以给用户名加一个索引，然后通过用户名查就好了，这样效率更
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res == null)
            throw new ServiceException("404", "用户名不存在");
        if (!res.getPassword().equals(user.getPassword()))
            throw new ServiceException("404", "密码错误");
        if (res.getRole() != 1)
            throw new ServiceException("404", "当前用户权限不足");
        // 生成 token，用户id保存到token里面，然后密码用于加密
        String token = TokenUtils.genToken(res.getId().toString());
        return new UserDto(res, token);
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public Page<User> findPage(Integer pageNum, Integer pageSize, String search) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        //新建模糊查询对象,这里有个注意事项，你模糊项查询的对应项不能为null，为null就查不出来
        if (!search.isEmpty()) {
            queryWrapper.like(User::getUsername, search);
        }
        return userMapper.selectPage(page, queryWrapper);
    }
}
